package com.ifp.opengate.boot.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import com.ifp.opengate.boot.gateway.config.ConsumerInMemoryRouteDefinitionRepository;

import reactor.core.publisher.Mono;

/**
 * 动态路由服务
 */
@Service
public class DynamicRouteService implements ApplicationEventPublisherAware {

    @Autowired
    RouteDefinitionWriter routeDefinitionWriter;
    @Autowired
    private RouteLocator routeLocator;
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    // 增加路由
    public void add(RouteDefinition definition) {
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "add success routeId: {} success" + definition.getId());

        } catch (Exception e) {
            // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "add route error " + e);

        }
    }

    // 更新路由
    public void update(RouteDefinition definition) {
        try {
            delete(definition.getId());
        } catch (Exception e) {
            // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "update fail,not find route routeId: " +
            // definition.getId());
        }
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "update success routeId: {} success" +
            // definition.getId());
        } catch (Exception e) {
            // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "update fail,not find route routeId: {} success" +
            // definition.getId());
        }
    }

    // 删除路由
    public void delete(String id) {
        ((ConsumerInMemoryRouteDefinitionRepository)this.routeDefinitionWriter).delete(id);
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
        // Trace.log(Trace.MODULE_TRACE, Trace.LEVEL_INFO, "delete success routeId: {} success" + id);
    }
}
